<script setup lang="ts">
import { MsgType, OrderType } from '@/enums'
import { useUserStore } from '@/stores'
import type { ConsultOrderItem } from '@/types/consult'
import type { Message, TimeMessages } from '@/types/room'
import { baseURL } from '@/utils/request'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { onMounted, onUnmounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import RoomAction from './components/RoomAction.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomStatus from './components/RoomStatus.vue'
import { getConsultOrderDetail } from '@/services/consult'

const store = useUserStore()
const route = useRoute()

let socket: Socket

const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()

// 组件挂载完毕后，进行socket连接
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data

  // 建立链接，创建 socket.io 实例
  socket = io(baseURL, {
    auth: { token: `Bearer ${store.user?.token}` },
    query: { orderId: route.query.orderId }
  })
  // 检查是否连接成功
  socket.on('connect', () => {
    console.log('connect')
  })
  // 错误异常消息
  socket.on('error', () => {
    console.log('error')
  })
  // 已经断开连接
  socket.on('disconnect', () => {
    console.log('disconnect')
  })

  // 聊天记录
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    const arr: Message[] = []
    data.forEach((item) => {
      // 数组最前项
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      // 其他数组项
      arr.push(...item.items)
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)
  })
  // 订单状态
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
})

// 组件卸载时，关闭连接
onUnmounted(() => socket.close())
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="问诊室" />
    <!-- 状态栏组件 -->
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <!-- 消息卡片组件 -->
    <room-message :list="list" />
    <!-- 操作栏组件 -->
    <room-action :disabled="consult?.status !== OrderType.ConsultChat" />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  min-height: 100vh;
  background-color: var(--cp-bg);
  padding-top: 90px;
  padding-bottom: 60px;
  box-sizing: border-box;
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
